﻿using System.IO;
using System.Xml.Xsl;
using System;

namespace GSMock.Resources
{
    public class StylesheetManager : FileBasedCacheManager
    {
        /// <summary>
        ///   Gets a stylehseet.
        /// </summary>
        /// <param name="name">The name of the stylesheet to retrieve.</param>
        /// <returns>
        ///   The stylesheet loaded into an XslCompiledTransform object.
        /// </returns>
        public XslCompiledTransform GetStylesheet(string name)
        {
            XslCompiledTransform transform = this.GetFromCache(name) as XslCompiledTransform;

            if (transform == null)
            {
                var stylesheet = Config.Configuration.GetConfig().Stylesheets[name];

                if (stylesheet != null)
                {
                    string filePath = this.HttpConext.Server.MapPath(stylesheet.File);

                    // Get from disk.
                    transform = this.GetFromDisk(filePath);

                    // Add to cache for next time.
                    this.AddToCache(name, transform, filePath);
                }
                else
                {
                    throw new ApplicationException(
                        string.Format("No stylesheet configured for name:{0}", name));
                }
            }

            return transform;
        }

        /// <summary>
        ///   Gets the results from disk.
        /// </summary>
        /// <param name="filePath">
        ///   The file path to the results file.
        /// </param>
        /// <returns>
        ///   An XML document loaded with the results.
        /// </returns>
        private XslCompiledTransform GetFromDisk(string filePath)
        {
            if (System.IO.File.Exists(filePath))
            {
                XslCompiledTransform transform = new XslCompiledTransform();
                transform.Load(filePath);

                return transform;
            }
            else
            {
                throw new FileNotFoundException(
                    string.Format("Cannot find results file: {0}.", filePath));
            }
        }

    }
}
